package com.runrunfast.fxj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.runrunfast.fxj.form.PageForm;
import com.runrunfast.fxj.vo.PageVo;
import com.runrunfast.fxj.vo.SysUserAddVo;
import com.runrunfast.fxj.vo.SysUserVo;
import com.runrunfast.fxj.entity.SysUser;
import com.runrunfast.fxj.entity.SysUserRole;
import com.runrunfast.fxj.exception.FxjException;
import com.runrunfast.fxj.mapper.SysUserMapper;
import com.runrunfast.fxj.mapper.SysUserRoleMapper;
import com.runrunfast.fxj.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 陈胤训
 * @since 2019-03-12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Autowired
    private  SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public List<SysUser> listByRoleId(Integer roleId) {
        return baseMapper.selectList(new QueryWrapper<SysUser>().eq("sys_user_id",roleId));
    }

    @Override
    @Transactional
    public Boolean add(SysUserAddVo user) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        if (baseMapper.insert(sysUser) == 0){
            throw new FxjException(21,"用户插入失败");
        }
        SysUserRole build = SysUserRole.builder().sysUserId(sysUser.getSysUserId()).sysRoleId(user.getSysRoleId()).build();
        if (userRoleMapper.insert(build) == 0){
            throw new FxjException(22,"用户角色关系插入失败");
        }
        return true;
    }

    @Override
    public Boolean updateInfo(SysUserVo userVO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userVO,sysUser);
        int i = baseMapper.updateById(sysUser);
        return 0 >= i ;
    }

    @Override
    public PageVo<SysUserVo> getPageUserList(PageForm pageVo, String username) {
        int count = baseMapper.selectCount(new QueryWrapper<>());
        List<SysUser>  sysUserVO =  userMapper.getPageUserList(pageVo,username);
        List<SysUserVo> pageUserList1 = userMapper.getPageUserList1(pageVo, username);


        return  PageVo.<SysUserVo>builder().current(pageVo.getCurrent()).size(pageVo.getSize()).records(pageUserList1).total(count).build();
    }
}
